import styled from '@emotion/styled';
import { Layout } from 'antd';
import AgentService, { Agent } from '../../../public/widget';

const { Header } = Layout;

import React, { useEffect, useState } from 'react';
import HeaderMenu from '../HeaderMenu';
import { useNavigate } from 'react-router-dom';
import { osslogin } from '@/api';
import useSyncState from '@/hooks/useSyncState';

const HomeContainer = styled.div`
	width: 100%;
	background: none;
	height: 100%;
	overflow: hidden;
`;

const HeaderWrapper = styled(Header)`
	height: 60px;
	padding: 0px;
	background: #ffffff;
	box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.1);
	margin-bottom: 12px;
`;



/** 环境区分 */
const ctx = {
	isTEST: process.env.TARGET_ENV?.includes('test'),
	isSSO: process.env.TARGET_ENV?.includes('sso')
};



const Home = () => {
	const nav = useNavigate();
	const [loginData, setLoginData] = useSyncState<any>(null);

	useEffect(() => {
		console.log('Home ctx', ctx);
		if (ctx.isTEST) {
			console.log('isLogin', sessionStorage.getItem('isLogin'));
			if (!sessionStorage.getItem('isLogin')) {
				nav('/login', { replace: true });
			}
	
			window.onunload = () => {
				sessionStorage.removeItem('isLogin');
			};
		} else {
			const code = getQueryStringByName('code');
			if (code) {
				ossloginSystem({ code });
			} else {
				nav('/osslogin', { replace: true });
			}
		}
	}, []);

	const loginAms = async (data: any) => {
		try {
			AgentService.Agent.ssologinSystem(
				data,
				resp => {
					console.log(resp);
					setLoginData(data);
					nav('/', { replace: true });
				},
				error => {
					console.log(error);
				}
			);
		} catch (error) {
			console.error(error);
		}
	};

	const ossloginSystem = async (params: { code: string }) => {
		try {
			const { data } = await osslogin(params);
			if (data.code === '0000') {
				loginAms(data.data);
			} else {
				nav('/osslogin', { replace: true });
			}
		} catch (error) {
			nav('/osslogin', { replace: true });
			console.log(error);
		}
	};

	const getQueryStringByName = (name: string) => {
		let result1 = document.location.search.match(new RegExp('[\\?\\&]' + name + '=([^\\&]+)', 'i'));
		let result2 = document.location.hash && document.location.hash.match(new RegExp('[\\?\\&]' + name + '=([^\\&]+)', 'i'));
		let result = result1 || result2;
		if (result === null || result.length < 1) {
			return '';
		}
		return result[1];
	};

	// useEffect(() => {
	// 	const code = getQueryStringByName('code');
	// 	if (code) {
	// 		ossloginSystem({ code });
	// 	} else {
	// 		nav('/osslogin', { replace: true });
	// 	}
	// }, []);

	return (
		<HomeContainer>
			<Layout>
				<HeaderWrapper>
					<HeaderMenu loginData={loginData()} />
				</HeaderWrapper>
			</Layout>
		</HomeContainer>
	);
};

export default Home;
